package com.jhws.business.alert.service;


import java.util.List;

import javax.annotation.Resource;

import com.jhws.business.alert.dao.TblServiceDimHibernateDAO;
import com.jhws.sys.appUser.service.AppUserService;
import com.jhws.business.comm.service.CommService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.alert.bo.TblServiceDimBo;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.util.GetId;
import com.jhws.core.db.BaseDao;
import com.jhws.core.push.PushXinGe;
import com.jhws.business.alert.bo.Alarm;

@Service
public class AlertService {
	private BaseDao dao = new BaseDao();
	
	@Resource 
	private TblServiceDimHibernateDAO tblServiceDimDAO;
	
	@Resource 
	private CommService cs;
	
	@Resource 
	private AppUserService aus;
	

	/**
	 * 保存报警信息
	 * @param a
	 */
	public void saveAlarm(Alarm a) {
		TblServiceDimBo bo = new TblServiceDimBo();
		bo.setSerCode(GetId.randomID());
		bo.setCreateTime(a.getAlarmDate());
		bo.setType(String.valueOf(a.getAlarmType()));
		String sip = a.getSipNum();
		String roomInfo = "";
		if(!StringUtils.isEmpty(sip) && sip.length() == 12){
			String comm = sip.substring(0,4);
			String dong = sip.substring(4,6);
			String unit = sip.substring(6,8);
			String floor = sip.substring(8,10);
			String room = sip.substring(10,12);
			roomInfo = cs.queryCommName(comm)+Integer.valueOf(dong) + "栋"+Integer.valueOf(unit) + "单元"+Integer.valueOf(floor) + "楼"+Integer.valueOf(room) + "房";
		}
		
		bo.setCreateUsr(sip);
		tblServiceDimDAO.save(bo);

		if(a.getAlarmType() == 1){
			a.setAlarmStringType("紧急报警");
		}else if(a.getAlarmType() == 2){
			a.setAlarmStringType("煤气报警");
		}else if(a.getAlarmType() == 3){
			a.setAlarmStringType("烟感报警");
		}else if(a.getAlarmType() == 4){
			a.setAlarmStringType("门磁报警");
		}else if(a.getAlarmType() == 5){
			a.setAlarmStringType("红外报警");
		}
		JsonRespData resp = new JsonRespData("alert", 1, a);
        String jsonString = JSON.toJSONString(resp);
		
		List<String> mobiles = aus.queryMobile(sip);
		if(mobiles.size() > 0){
			for (String mobile : mobiles) {
				PushXinGe.androidPushSingleAccount(mobile, "alarm_json", jsonString);
				PushXinGe.iosPushSingleAccount(mobile, "CP", a.getAlarmStringType(), jsonString);
			}
		}
		
		PushXinGe.androidPushSingleAccount(sip, "alarm_json", jsonString);
		PushXinGe.androidPushSingleAccount(sip.substring(0,4)+"00000001", "alarm_json", jsonString);
		PushXinGe.iosPushSingleAccount(sip, "CP", a.getAlarmStringType(), jsonString);
	}
}
